package com.norma.netty.study.nio;

import lombok.SneakyThrows;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author zhangchaofeng
 * @date 2020/10/2
 * @description 多人运动客户端
 */
public class GroupChatClient {

    private static final String HOST = "localhost";

    private static final int PORT = 6667;

    private Selector selector;

    private SocketChannel socketChannel;

    private String userName;

    public GroupChatClient() throws IOException {
        selector = Selector.open();
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        if (!socketChannel.connect(new InetSocketAddress(HOST, PORT))) {
            while (!socketChannel.finishConnect()) {
                System.out.println("客户端连接中...");
            }
        }
        //将socketChannel注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        userName = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println("客户端" + userName + "连接服务端成功~");
    }

    /**
     * 发送消息
     */
    @SneakyThrows
    private void sendData(String msg) {
        msg = userName + "说: " + msg;
        ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
        socketChannel.write(byteBuffer);
    }

    /**
     * 读取消息
     */
    private void receiveData() throws Exception {
        //阻塞读取消息
        selector.select();
        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            SelectionKey selectionKey = iterator.next();
            SelectableChannel channel = selectionKey.channel();
            if (channel instanceof SocketChannel) {
                SocketChannel socketChannel = (SocketChannel) channel;
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                socketChannel.read(byteBuffer);
                //从缓冲区拿出消息
                System.out.println(new String(byteBuffer.array()));
            }
            //删除已经处理过的Key
            iterator.remove();
        }

    }

    public static void main(String[] args) throws Exception {
        GroupChatClient client = new GroupChatClient();

        //开启线程接收数据
        new Thread(() -> {
            try {
                while (true) {
                    client.receiveData();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            client.sendData(msg);
        }

    }


}
